package com.example.lexiangbackend.service;

import com.example.lexiangbackend.dto.CategoryRequest;
import com.example.lexiangbackend.entity.MusicCategory;
import com.example.lexiangbackend.repository.MusicCategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class CategoryService {

    @Autowired
    private MusicCategoryRepository categoryRepository;

    /**
     * 创建分类
     */
    public MusicCategory createCategory(CategoryRequest request) {
        // 检查分类名是否已存在
        if (categoryRepository.findByName(request.getName()).isPresent()) {
            throw new RuntimeException("分类名称已存在");
        }

        MusicCategory category = new MusicCategory();
        category.setName(request.getName());
        category.setDescription(request.getDescription());
        category.setColor(request.getColor() != null ? request.getColor() : "#1DB954");
        category.setGradient(request.getGradient());
        category.setIcon(request.getIcon() != null ? request.getIcon() : "🎵");
        category.setSortOrder(request.getSortOrder() != null ? request.getSortOrder() : 0);
        category.setStatus(request.getStatus() != null ? request.getStatus() : 1);

        return categoryRepository.save(category);
    }

    /**
     * 获取所有分类（带排序）
     */
    public List<MusicCategory> getAllCategories() {
        return categoryRepository.findAll(Sort.by(Sort.Direction.ASC, "sortOrder"));
    }

    /**
     * 分页获取分类
     */
    public Page<MusicCategory> getCategories(int page, int size, String sortBy) {
        Sort sort = Sort.by(Sort.Direction.ASC, sortBy != null ? sortBy : "sortOrder");
        Pageable pageable = PageRequest.of(page, size, sort);
        return categoryRepository.findAll(pageable);
    }

    /**
     * 更新分类
     */
    public MusicCategory updateCategory(Long categoryId, CategoryRequest request) {
        Optional<MusicCategory> categoryOpt = categoryRepository.findById(categoryId);
        if (categoryOpt.isEmpty()) {
            throw new RuntimeException("分类不存在");
        }

        // 检查分类名是否已被其他分类使用
        Optional<MusicCategory> existingCategory = categoryRepository.findByName(request.getName());
        if (existingCategory.isPresent() && !existingCategory.get().getCategoryId().equals(categoryId)) {
            throw new RuntimeException("分类名称已存在");
        }

        MusicCategory category = categoryOpt.get();
        category.setName(request.getName());
        category.setDescription(request.getDescription());
        category.setColor(request.getColor());
        category.setGradient(request.getGradient());
        category.setIcon(request.getIcon());
        category.setSortOrder(request.getSortOrder());
        category.setStatus(request.getStatus());

        return categoryRepository.save(category);
    }

    /**
     * 删除分类
     */
    public void deleteCategory(Long categoryId) {
        if (!categoryRepository.existsById(categoryId)) {
            throw new RuntimeException("分类不存在");
        }
        
        // TODO: 检查是否有音乐使用此分类，如果有则不允许删除
        // 或者可以选择级联删除或转移到其他分类
        
        categoryRepository.deleteById(categoryId);
    }

    /**
     * 批量删除分类
     */
    public void deleteCategoriesBatch(List<Long> categoryIds) {
        for (Long categoryId : categoryIds) {
            if (categoryRepository.existsById(categoryId)) {
                categoryRepository.deleteById(categoryId);
            }
        }
    }

    /**
     * 批量更新分类状态
     */
    public void updateCategoriesStatus(List<Long> categoryIds, Integer status) {
        for (Long categoryId : categoryIds) {
            Optional<MusicCategory> categoryOpt = categoryRepository.findById(categoryId);
            if (categoryOpt.isPresent()) {
                MusicCategory category = categoryOpt.get();
                category.setStatus(status);
                categoryRepository.save(category);
            }
        }
    }

    /**
     * 根据ID获取分类
     */
    public MusicCategory getCategoryById(Long categoryId) {
        return categoryRepository.findById(categoryId)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
    }

    /**
     * 获取分类总数
     */
    public long getCategoryCount() {
        return categoryRepository.count();
    }

    /**
     * 根据名称搜索分类
     */
    public List<MusicCategory> searchCategories(String keyword) {
        // 这里应该在Repository中实现搜索方法
        return categoryRepository.findAll();
    }

    /**
     * 根据状态获取分类
     */
    public List<MusicCategory> getCategoriesByStatus(Integer status) {
        return categoryRepository.findAll().stream()
                .filter(category -> category.getStatus().equals(status))
                .sorted((a, b) -> a.getSortOrder().compareTo(b.getSortOrder()))
                .toList();
    }
} 